// 主体组件
import '../sidebar'
import '../content'
import 'styles/loading.css'
import SideBar from '../sidebar';
import render from '../content/content.art'
import renderLoading from 'components/loading/loading.art'
import { get,set } from 'utils/storage';
import { SESSION_STORAGE_NAME,SIDEBAR_ITEM_CLASSNAME } from './constants';
import BackTop from 'components/backTop';
import Content from '../content';

const ul = document.getElementById('sidebarList');

const sidebar = new SideBar(ul);
const content = new Content(document.getElementById('content'));

// 事件委托
ul.addEventListener('click',e => {
    // 判断是否为li
    if(e.target.classList.contains(SIDEBAR_ITEM_CLASSNAME)){
        // 改变li的样式
        sidebar.change(e.target);
        const name = SESSION_STORAGE_NAME+e.target.dataset.id;
        // 判断缓存中是否有数据
        if(get(name)){
            // 有点的话直接渲染
            content.setText(render({data:get(name)}));
        }else{
            // 没有的话 ，先显示loading图标
            content.setText(renderLoading());
            // 发送请求
            sidebar.getData(e.target.dataset.id)
            .then(data => {
                content.setText(render({data:data}));
                // 同时将结果存到会话缓存中
                set(name,data)
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
})

// 调用返回顶部按钮类
new BackTop(document.getElementById('content'));

// 触发一下第一个点击
ul.children[0].click();

